/*global PhiloGL*/
import { watch } from "@vue/runtime-core"
export function init(actionContent) {
  PhiloGL.unpack()

  actionContent.forEach((item) => {
    watch(
      () => item,
      (val) => {
        if (val.title === "样条线曲率") {
          curviness = val.value
          render(canvas, ctx, bundle, delta, type, curviness)
        } else if (val.title === "绑定度数") {
          delta = val.value
          render(canvas, ctx, bundle, delta, type, curviness)
        } else if (val.title === "扇入扇出角") {
          console.log(1111111111)
          angleStrength = val.value
          debugger
          render(canvas, ctx, bundle, delta, type, curviness)
        } else if (val.title === "绑定邻节点数") {
          neighbors = val.value
          debugger
          render(canvas, ctx, bundle, delta, type, curviness)
        } else if (val.title === "边距") {
          margin = val.value
          render(canvas, ctx, bundle, delta, type, curviness)
        } else if (val.title === "线的类型") {
          type = val.value
          render(canvas, ctx, bundle, delta, type, curviness)
        } else if (val.title === "线的透明度") {
          alpha = val.value
          render(canvas, ctx, bundle, delta, type, curviness)
        } else if (val.title === "线的样式") {
          colorType = val.value
          render(canvas, ctx, bundle, delta, type, curviness)
        }
      },
      { deep: true }
    )
  })

  var delta = 1,
    type = "Bezier",
    neighbors = 10,
    angleStrength = 3,
    curviness = 1,
    margin = 0,
    alpha = 1, // 0.5
    // color = '#00cccc',
    color = "#F00", // 线的颜色
    // clusterColors = ["#F00", "#0F0", "#00F", "#FF0", "#F0F", "#0FF", "#F0F0F0", "#CCEBC5", "#B3DE69", "#BC80BD", "#FFED6F"],
    clusterColors = [
      "#F00",
      "#0F0",
      "#00F",
      "#FF0",
      "#F0F",
      "#0FF",
      "#F0F0F0",
      "#0F0F0F",
      "#00F0F0",
      "F0F000",
      "0F0F00",
    ],
    colorType = "Solid",
    counter = 0,
    dataset = "philippines",
    canvas = document.querySelector("canvas#renderer"),
    background = document.querySelector(".world-map"),
    dotsCanvas = document.querySelector("canvas#dots"),
    ctx = canvas.getContext("2d"),
    dotsCtx = dotsCanvas.getContext("2d"),
    ink = document.querySelector("#ink"),
    container = document.querySelector(".container"),
    directionSort = function (a, b) {
      var aColor, bColor
      if (Array.isArray(a.data.color)) {
        aColor = a.data.color[0]
        bColor = b.data.color[0]
        if (aColor == bColor) {
          return 0
        }
        return aColor > bColor ? 1 : -1
      }
    },
    xSort = function (a, b) {
      var diffX = a.data.coords[0] - b.data.coords[0],
        diffY = a.data.coords[1] - b.data.coords[1]
      if (!diffX) {
        return diffY
      }
      return diffX
    },
    ySort = function (a, b) {
      var diffX = a.data.coords[0] - b.data.coords[0],
        diffY = a.data.coords[1] - b.data.coords[1]
      if (!diffY) {
        return diffX
      }
      return -diffY
    },
    componentSort = function (a, b) {
      var diffX = Math.abs(a.data.coords[0] - b.data.coords[2]),
        diffY = Math.abs(a.data.coords[1] - b.data.coords[3])

      return diffX > diffY ? ySort(a, b) : xSort(a, b)
    },
    sortOptions = [null, componentSort, xSort, ySort, directionSort],
    sortType = null,
    options,
    imageData,
    jsonText,
    json,
    bundle,
    loader

  function updateBundle() {
    bundle.options.angleStrength = angleStrength
    bundle.options.sort = sortType
    bundle.setNodes(JSON.parse(jsonText))
    //ensure the direction is calculated before computing the graph.
    bundle.graph.each(function (n) {
      if (colorType == "Direction") {
        if (!Array.isArray(n.data.color)) {
          n.data.color =
            Math.random() > 0.5 ? ["#0083ce", "#cf4846"] : ["#0083ce", "#cf4846"].reverse()
        }
      }
    })
    bundle.buildNearestNeighborGraph(neighbors)
    bundle.MINGLE()
  }

  function calculateInk() {
    imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data
    for (var i = 0, l = imageData.length, acum = 0; i < l; i += 4) {
      if (imageData[i + 3] != 0) {
        acum++
      }
    }
    ink.innerText = Math.round((acum / (canvas.width * canvas.height)) * 10000) / 100
  }

  ;(function loop() {
    Fx.requestAnimationFrame(loop)
  })()

  function animate(bundle, canvas, ctx) {
    var loading = document.querySelector(".loading")
    if (loading && loading.parentNode) {
      loading.parentNode.removeChild(loading)
    }

    new Fx({
      transition: Fx.Transition.Quart.easeInOut,
      duration: 1000,
    }).start({
      onCompute: function (epsilon) {
        delta = epsilon
        render()
      },
    })
  }

  dotsCanvas = document.querySelector("canvas#dots")
  dotsCtx = dotsCanvas.getContext("2d")

  function renderPoints() {
    dotsCtx.fillStyle = "#000"
    dotsCanvas.width = dotsCanvas.width
    json.forEach(function (edge) {
      // 绘制
      dotsCtx.beginPath() // 开启绘制路径
      // 绘制圆 参数依次为 圆的横坐标/纵坐标/半径/绘制圆的起始位置/绘制圆的弧度大小
      dotsCtx.arc(
        edge.data.coords[0],
        edge.data.coords[1],
        options.radius || 1,
        0,
        Math.PI * 2,
        false
      )
      // 点的颜色
      dotsCtx.fillStyle = "rgba(255,255,255,.7)" //"rgba(255,255,255,.5)"; // 设置填充颜色
      dotsCtx.fill()
      dotsCtx.closePath()
      dotsCtx.beginPath()
      // dotsCtx.strokeStyle = {width:'10px'}
      dotsCtx.arc(
        edge.data.coords[2],
        edge.data.coords[3],
        options.radius || 1,
        0,
        Math.PI * 2,
        false
      )
      dotsCtx.fill()
      dotsCtx.closePath() // 关闭绘制路径
    })
  }

  document.onmousemove = function (e) {
    debounce(createDot(e), 1000) // 未生效  window.addEventListener('scroll', debounce(handle, 1000));
  }
  // document.addEventListener('mousemove', createDot); // 添加点击事件
  let divLabel = document.createElement("div")
  divLabel.style.backgroundColor = "rgba(0,255,0,0.5)" //'rgba(0,255,0,0.5)' 标签颜色
  divLabel.style.width = "150px"
  divLabel.style.lineHeight = "30px"
  divLabel.style.display = "none"
  divLabel.style.position = "absolute"
  document.querySelector(".container").appendChild(divLabel)

  // 防抖和节流函数，暂未用到
  var throttle = function (func, delay) {
    var prev = Date.now()
    return function () {
      var context = this //this指向window
      var args = arguments
      var now = Date.now()
      if (now - prev >= delay) {
        func.apply(context, args)
        prev = Date.now()
      }
    }
  }
  function debounce(fn, wait) {
    var timeout = null //定义一个定时器
    return function () {
      if (timeout !== null) clearTimeout(timeout) //清除这个定时器
      timeout = setTimeout(fn, wait)
    }
  }

  function createDot(e) {
    // 点击事件方法
    var tx = e.offsetX,
      ty = e.offsetY // 获取点击位置
    if (tx > 414 && tx < 940 && ty > 82 && ty < 468) {
      // 判断是都在canvas内 width和height为canvas宽高
      divLabel.style.display = "block"
      divLabel.innerText = "CVE-2019-12614" //+String(Math.floor(Math.random()*2000)+3000)
      divLabel.style.left = tx + "px"
      divLabel.style.top = ty + "px"
    } else {
      divLabel.style.display = "none"
    }
  }

  function render() {
    canvas.width = canvas.width
    ctx.strokeStyle = "rgba(0, 200, 200, 1)"
    ctx.lineWidth = 1
    counter = 0
    bundle.graph.each(function (node) {
      var i = counter
      if (node.data.nodeArray) {
        // debugger
        node.data.nodeArray.forEach(function (n, j) {
          if (colorType == "Cluster") {
            n.data.color = clusterColors[i % clusterColors.length]
          } else if (colorType == "Solid") {
            n.data.color = color
          } else if (colorType == "Edge") {
            n.data.color = clusterColors[j % clusterColors.length]
          } else if (colorType == "Direction") {
            if (!Array.isArray(n.data.color)) {
              n.data.color =
                Math.random() > 0.5 ? ["#0083ce", "#cf4846"] : ["#0083ce", "#cf4846"].reverse()
            }
          }
          n.data.alpha = alpha
        })
      }
      var edges = node.unbundleEdges(delta)
      Bundler.Graph["render" + type](ctx, edges, {
        delta: delta,
        margin: margin,
        curviness: curviness,
        scale: options.scale,
      })
      counter++
    })
    calculateInk()
  }

  // 绑定度数
  // var bundleLabel = document.querySelector("#bundle-level-span")
  // bundleLabel.innerText = Math.round(delta * 1000) / 10 + "%"
  // document.querySelector("#bundle-level").addEventListener("mousemove", function () {
  //   delta = +this.value
  //   bundleLabel.innerText = Math.round(delta * 1000) / 10 + "%"
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 样条线曲率
  // var curvinessLabel = document.querySelector("#curviness-span")
  // curvinessLabel.innerText = Math.round(curviness * 1000) / 10 + "%"
  // document.querySelector("#curviness").addEventListener("mousemove", function () {
  //   curviness = +this.value
  //   curvinessLabel.innerText = Math.round(curviness * 1000) / 10 + "%"
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 边距
  // var marginLabel = document.querySelector("#margin-span")
  // marginLabel.innerText = Math.round(margin * 10) / 10
  // document.querySelector("#margin").addEventListener("mousemove", function () {
  //   margin = +this.value
  //   marginLabel.innerText = Math.round(margin * 10) / 10
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 扇入扇出角
  // var angleLabel = document.querySelector("#angle-strength-span")
  // angleLabel.innerText = Math.round(angleStrength * 10) / 10
  // document.querySelector("#angle-strength").addEventListener("change", function () {
  //   angleStrength = +this.value
  //   angleLabel.innerText = Math.round(angleStrength * 10) / 10
  //   updateBundle()
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 绑定邻节点数
  // var neighborsLabel = document.querySelector("#neighbors-span")
  // neighborsLabel.innerText = Math.round(neighbors * 10) / 10
  // document.querySelector("#neighbors").addEventListener("change", function () {
  //   neighbors = +this.value
  //   neighborsLabel.innerText = Math.round(neighbors * 10) / 10
  //   updateBundle()
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 线的类型
  // document.querySelector("#line-type").addEventListener("change", function () {
  //   type = this.value
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 线的颜色
  // document.querySelector("#color").addEventListener("change", function () {
  //   color = this.value
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 线的透明度
  // var alphaLabel = document.querySelector("#alpha-span")
  // alphaLabel.innerText = Math.round(alpha * 10) / 10
  // document.querySelector("#alpha").addEventListener("mousemove", function () {
  //   alpha = this.value
  //   alphaLabel.innerText = Math.round(alpha * 10) / 10
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 线的颜色
  // document.querySelector("#color-type").addEventListener("change", function () {
  //   colorType = this.value
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  // 数据源
  // document.querySelector("#dataset").addEventListener("change", function () {
  //   dataset = this.value
  //   load()
  // })

  // Edge Group
  // document.querySelector("#sort-type").addEventListener("change", function () {
  //   sortType = sortOptions[this.selectedIndex]
  //   updateBundle()
  //   render(canvas, ctx, bundle, delta, type, curviness)
  // })

  loader = new Loader()
  function load() {
    options = loader.load(dataset, {
      complete: function (data) {
        if (!data.length) {
          console.warn("no data returned")
          return
        }
        if (data.length > 5e3) {
          console.warn("data is too big", data.length)
          return
        }
        background.className = "world-map " + dataset
        canvas.width = dotsCanvas.width = options.width
        canvas.height = dotsCanvas.height = options.height

        canvas.style.width = dotsCanvas.style.width = options.width / (options.ratio || 1) + "px"
        canvas.style.height = dotsCanvas.style.height = options.height / (options.ratio || 1) + "px"

        container.style.width = canvas.offsetWidth + "px"
        background.style.width = canvas.offsetWidth + "px"
        background.style.height = canvas.offsetHeight + "px"

        json = data
        renderPoints()
        jsonText = JSON.stringify(json)
        console.time("MINGLE")
        bundle = new Bundler()
        bundle.options.angleStrength = angleStrength
        bundle.options.sort = sortType
        bundle.setNodes(json)
        bundle.graph.each(function (n) {
          if (colorType == "Direction") {
            if (!Array.isArray(n.data.color)) {
              n.data.color =
                Math.random() > 0.5 ? ["#0083ce", "#cf4846"] : ["#0083ce", "#cf4846"].reverse()
            }
          }
        })
        bundle.buildNearestNeighborGraph(neighbors)
        bundle.MINGLE()
        console.timeEnd("MINGLE")
        animate(bundle, canvas, ctx)
      },
    })
  }
  load()
}
